<?php

namespace app\api\controller\user;

use addons\shop\model\UserM;
use app\common\controller\Api;
use app\common\library\Auth;
use Exception;
use think\Cookie;
use Throwable;

class LoginByWechatCode extends Api
{
    protected $noNeedLogin = '*';

    public function index()
    {
        $code       = input('code');
        $app_id     = 'wx2538eed5333f4e62';
        $app_secret = '1fe9c31ff382ea6a9c01c343e175464b';
        try {
            $oauth2   = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$app_id&secret=$app_secret&code=$code&grant_type=authorization_code");
            $oauth2   = json_decode($oauth2, true);
            $userinfo = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$oauth2[access_token]&openid=$oauth2[openid]");
            $userinfo = json_decode($userinfo, true);
            $user     = UserM::where(['openid' => $userinfo['openid']])->find();
            if (empty($user)) {
                $user = UserM::create([
                    'status' => 'normal',
                    'openid' => $userinfo['openid'],
                ]);
            }
            $user->save([
                'nickname' => $userinfo['nickname'],
                'avatar'   => $userinfo['headimgurl'],
                'gender'   => $userinfo['sex'],
            ]);
            $auth = Auth::instance();
            if (!$auth->direct($user['id'])) {
                throw new Exception($auth->getError());
            }
            Cookie::set('uid', $user['id']);
            Cookie::set('token', $auth->getToken());
            header('location:/index/user/index');
        } catch (Throwable $e) {
            echo "{$e->getMessage()}<script>setTimeout(()=>history.go(-1),2000)</script>";
        }
    }
}